import { VuexModule, Module, Mutation, Action, getModule } from 'vuex-module-decorators';
import { login, logout, getUserInfo } from '@/api/user';
import { getToken, setToken, removeToken, setUserName, removeUserName } from '@/utils/cookies';
import store from '@/store';


export interface IUserState {
    token: string
    name: string
    avatar: string
    introduction: string
    roles: string[]
}

@Module({ dynamic: true, store, name: 'user' })
class User extends VuexModule implements IUserState {
    public token = getToken() || ''
    public name = ''
    public avatar = ''
    public userId = ''
    public introduction = ''
    public roles: string[] = []

    @Mutation
    private SET_TOKEN(token: string) {
        this.token = token
    }

    @Mutation
    private SET_NAME(name: string) {
        this.name = name
    }

    @Mutation
    private SET_USER_ID(userId: string) {
        this.userId = userId
    }

    @Mutation
    private SET_AVATAR(avatar: string) {
        this.avatar = avatar
    }

    @Mutation
    private SET_INTRODUCTION(introduction: string) {
        this.introduction = introduction
    }

    @Mutation
    private SET_ROLES(roles: string[]) {
        this.roles = roles
    }

    @Action
    public async Login(userInfo: { username: string, password: string }) {
        let { username, password } = userInfo
        username = username.trim()
        const { data } = await login({ username, password })
        const tokenStr = data.tokenHead + data.token
        setToken(tokenStr);
        this.SET_TOKEN(tokenStr)
    }

    @Action
    public async GetUserInfo() {
        if (this.token === '') {
            throw Error('GetUserInfo: token is undefined!');
        }
        const { data } = await getUserInfo();
        console.log('getUserInfo xxxxxxxx data = ', data);
        if (!data) {
            throw Error('Verification failed, please Login again.')
        }
        const { roles, username, userId, avatar, introduction } = data
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
            throw Error('GetUserInfo: roles must be a non-null array!')
        }
        this.SET_ROLES(roles)
        this.SET_NAME(username)
        this.SET_USER_ID(userId)
        setUserName(username);
        this.SET_AVATAR(avatar)
        this.SET_INTRODUCTION(introduction)
    }

    @Action
    public ResetToken() {
        removeToken()
        this.SET_TOKEN('')
        this.SET_ROLES([])
    }

    @Action
    public async LogOut() {
        if (this.token === '') {
            throw Error('LogOut: token is undefined!')
        }
        await logout()
        removeToken()
        this.SET_TOKEN('')
        removeUserName();
        this.SET_NAME('');
        this.SET_USER_ID('')
        this.SET_ROLES([])
    }


}

export const UserModule = getModule(User);
